#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from django.http.response import HttpResponse
from django.shortcuts import render
from django.template import loader, Context
from django.utils.dateparse import parse_date

import db
from store_manage import utils
from store_manage.utils import session


def index(request):
    template = loader.get_template('index.html')
    user = session.get_user(request)
    if user:
        context = Context({'username': user.username})
    else:
        context = Context({})
    return HttpResponse(template.render(context))

def store_enter(request):
    '''
        入库：1. 记录一次OperationLog  2. 保存到Product
    '''
    number = request.POST.get('number')
    name = request.POST.get('name')
    model_name = request.POST.get('model_name')
    category = request.POST.get('category')
    unit = request.POST.get('unit')
    location = request.POST.get('location')
    count = request.POST.get('count')
    remark = request.POST.get('remark')

    try:
        product = db.models.Product.objects.get(number=eval(number))
        product.count += eval(count)
        product.save()
    except:
        product = db.models.Product(number=eval(number), name=name, model_name=model_name,
                                    category=category, unit=unit, location=location,
                                    count=eval(count), remark=remark)
        product.save()

    user = session.get_user(request)
    try:
        o = db.models.OperationLog(product=product, operation_type='入库',
                                   count=eval(count), remain=product.count,
                                   user=user.username, remark=remark)
        o.save()
    except:
        traceback.print_exc()

    return utils.create_success_dict()

def store_deliver(request):
    '''
        出库：1. 记录一次OperationLog  2. 保存到Product
    '''
    number = request.POST.get('number')
    count = request.POST.get('count')
    remark = request.POST.get('remark')

    try:
        product = db.models.Product.objects.get(number=eval(number))
    except:
        return utils.create_failure_dict(msg='错误的品号')
    product.count -= eval(count)
    product.save()

    user = session.get_user(request)
    o = db.models.OperationLog(operation_datetime=datetime.datetime.now(),
                               product=product, operation_type='出库',
                               count=eval(count), remain=product.count,
                               user=user.username, remark=remark)
    o.save()
    return utils.create_success_dict()

def product_list(request):
    q = db.models.Product.objects.all().values().order_by('number')
    return utils.create_success_dict(data={
        'records': list(q),
    })

def product_export(request):
    pass

def product_check(request):
    number = request.GET.get('number')
    q = db.models.Product.objects.filter(number=number)
    return utils.create_success_dict(exist=q.exists())

def product_number_list(request):
    q = db.models.Product.objects.values('number').distinct()
    q = q.values_list('number', flat=True)
    return utils.create_success_dict(data={
        'records': list(q),
    })

def operation_log_list(request):
    category = request.POST.get('category')
    start_date = request.POST.get('start_date')
    end_date = request.POST.get('end_date')

    q = db.models.OperationLog.objects.all()
    if category:
        q = q.filter(product__category=category)
    if start_date:
        s = datetime.datetime.combine(parse_date(start_date), datetime.time.min)
        q = q.filter(operation_datetime__gte=s)
    if end_date:
        e = datetime.datetime.combine(parse_date(end_date), datetime.time.max)
        q = q.filter(operation_datetime__lte=e)
    q = q.values('operation_datetime', 'product__number', 'product__name',
                 'product__model_name', 'operation_type', 'count',
                 'remain', 'product__category', 'user', 'remark')
    return utils.create_success_dict(data={
        'records': list(q),
    })

def operation_log_export(request):
    pass
